package com.cetsk.android.talkorigins;

import java.util.ArrayList;

import com.actionbarsherlock.app.SherlockListActivity;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FavoritesListActivity extends SherlockListActivity {
	ListView lv = null;
	FavoriteAdapter fa = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.claims_list);
		ArrayList<Claim> favorites = new ArrayList<Claim>();
		
		DatabaseHelper dbh = new DatabaseHelper(this);
		try {
			Cursor cu = dbh.getWritableDatabase().rawQuery("select c.* from Favorites f join Claims c on c.id = f.claimId order by Name ASC", null);
			if (cu != null) {
				cu.moveToFirst();
				int IdIndex = cu.getColumnIndex("Id"); 
				int NameIndex = cu.getColumnIndex("Name"); 
				int UrlIndex = cu.getColumnIndex("Url"); 
				if (cu.isFirst()) { 
					do { 
						Claim c = new Claim();
						c.setId(cu.getInt(IdIndex));
						c.setName(cu.getString(NameIndex));
						c.setUrl(cu.getString(UrlIndex));
						favorites.add(c); 
					} while (cu.moveToNext()); 
				}
			}
			cu.close();
		} catch(SQLException sqle){
			Log.e( this.getClass().getName(), "", sqle );
		} finally { 
            if (dbh != null) 
            	dbh.close(); 
		}

		fa = new FavoriteAdapter(getBaseContext(), R.layout.favorites_list_item, favorites);
		getListView().setAdapter(fa);
		

		lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				try{
					Claim favorite = (Claim) ((LinearLayout) view).getTag();
					Intent intent = new Intent(getApplicationContext(), ClaimViewActivity.class);
					intent.putExtra("claim",favorite);
					startActivityForResult(intent,0);
				} catch(Exception e){
					Log.e("Error",e.getMessage());
				}
			}
		});
		lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				int i = 0;
				try {
					menu.add(Menu.NONE, 1, ++i, "Delete");
				} catch (Exception e){
					Log.e("Error Creating Context menu",e.getMessage());
				}
			}
		});
	}
	public boolean onContextItemSelected(android.view.MenuItem item) {
	    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	    Claim f = (Claim) info.targetView.getTag();
		if(item.toString().equals("Delete")){
			SQLiteDatabase dbh = this.openOrCreateDatabase(DatabaseHelper.DBNAME, SQLiteDatabase.OPEN_READWRITE, null);
			try {
				dbh.execSQL("DELETE FROM " + DatabaseHelper.FAVORITES_TABLE + " WHERE Id="+f.getId());
			} catch (SQLException sqle){
				Toast.makeText(getApplicationContext(), R.string.remove_favorite_error, Toast.LENGTH_SHORT).show();
				Log.e("SQLError",sqle.getMessage());
			} finally {
				Toast.makeText(getApplicationContext(), R.string.remove_favorite_action, Toast.LENGTH_SHORT).show();
				fa.remove(f);
				lv.invalidateViews();
				dbh.close();
			}
		} else {
			
		}
    	return true;
    }
	private class FavoriteAdapter extends ArrayAdapter<Claim> {
		private ArrayList<Claim> items;

		public FavoriteAdapter(Context context, int textViewResourceId, ArrayList<Claim> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_item, null);
			}
			Claim f = items.get(position);
			
			if (f != null) {
				TextView tt = (TextView) v.findViewById(R.id.list_item_text);
				tt.setText(f.getName());
				
				LinearLayout ll = (LinearLayout) v.findViewById(R.id.list_item);
				ll.setTag(f);
			}
			return v;
		}
	}
}